package com.wsd.common.utils;

import com.wsd.common.entity.UserTokenEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


/**
 * jwt工具类
 */
@ConfigurationProperties(prefix = "wx.jwt")
@Component
@Slf4j
public class JwtUtils {

    private String secret;
    private String header;

    /**
     * 生成jwt token
     */
    public String generateToken(UserTokenEntity userToken) {
        // secret过短会有java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter异常
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userToken.getOpenId())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }


    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
